#!/usr/bin/python2.5

# Copyright 2009 Ferdjaoui Sahid.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


from common import models
from google.appengine.api import memcache


def user_get_or_create (uid):
  if not uid:
    return None

  key = 'actor/%s' % uid
  actor_ref = models.Actor.get_by_key_name (key)
  if not actor_ref:
    actor_ref = models.Actor (key_name = key, uid = uid)
    actor_ref.put ()
    
  return actor_ref


def entry_get_top_sended (limit = 10):
  return entry_get_top ('count_sended', limit)

def entry_get_top_received (limit = 10):
  return entry_get_top ('count_received', limit)

def entry_get_top (order_by, limit = 10):
  cache_key = '/entry_get_top/%s/%s' % (order_by, limit)
  
  data = memcache.get (cache_key)
  data = None
  if data is not None:
    return data
  else:
    query = ("WHERE %s > 0 ORDER BY %s DESC LIMIT 10") % (order_by, order_by)
    data  = models.Actor.gql (query)
    memcache.add (cache_key, data, 60)
    return data



